package online.westonline.com.westonline.ui;

import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.easy.west.westclient.api.workplan.baen.Event;
import com.easy.west.westclient.api.workplan.baen.EventList;
import com.easy.west.westclient.api.workplan.event.GetAllEvent;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarLayout;
import com.haibin.calendarview.CalendarView;
import com.wingsofts.byeburgernavigationview.ByeBurgerBehavior;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import online.westonline.com.westonline.MyApplication;
import online.westonline.com.westonline.R;
import online.westonline.com.westonline.adapter.MyEventListAdpter;
import online.westonline.com.westonline.base.BaseActivity;
import online.westonline.com.westonline.utils.ToastUtils;
import online.westonline.com.westonline.utils.UiUtlis;

public class WorkPlanListActivity extends BaseActivity implements CalendarView.OnDateSelectedListener,
        CalendarView.OnYearChangeListener {


    @BindView(R.id.calendarView)
    CalendarView calendarView;
    @BindView(R.id.calendarLayout)
    CalendarLayout calendarLayout;
    @BindView(R.id.recyclerView_event)
    RecyclerView recyclerViewEvent;
    @BindView(R.id.tv_month_day)
    TextView tvMonthDay;
    @BindView(R.id.tv_year)
    TextView tvYear;
    @BindView(R.id.tv_lunar)
    TextView tvLunar;
    @BindView(R.id.ib_calendar)
    ImageView ibCalendar;
    @BindView(R.id.tv_current_day)
    TextView tvCurrentDay;
    @BindView(R.id.fl_current)
    FrameLayout flCurrent;
    @BindView(R.id.rl_tool)
    RelativeLayout rlTool;
    @BindView(R.id.li_root)
    LinearLayout liRoot;
    @BindView(R.id.float_add_plan)
    FloatingActionButton floatAddPlan;
    @BindView(R.id.tv_topbar_title)
    TextView tvTopbarTitle;
    @BindView(R.id.tv_topbar_title_center)
    TextView tvTopbarTitleCenter;
    @BindView(R.id.img_toolbar_menu)
    ImageView imgToolbarMenu;
    @BindView(R.id.tv_topbar_menu)
    TextView tvTopbarMenu;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    private MyEventListAdpter eventListAdpter;
    //高博里的event
    private List<Event> eventLists = new ArrayList<>();
    private int selectday;
    private int mYear;

    @Override
    protected void initview() {
        //初始化toolbar
        toolbar.setBackgroundColor(UiUtlis.getColor(R.color.colorAppTheme));
        toolbar.setTitleTextColor(UiUtlis.getColor(R.color.colorMenuBtn));
        toolbar.setTitle("日程列表");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
        //
        mYear = calendarView.getCurYear();
        tvYear.setText(String.valueOf(calendarView.getCurYear()));
        mYear = calendarView.getCurYear();
        tvMonthDay.setText(calendarView.getCurMonth() + "月" + calendarView.getCurDay() + "日");
        tvLunar.setText("今日");
        tvCurrentDay.setText(String.valueOf(calendarView.getCurDay()));
        //绑定事件
        calendarView.setOnDateSelectedListener(this);
        calendarView.setOnYearChangeListener(this);
        //初始化recyclerview
        initrecyclerview();
        //初始化事件
        initsession();

    }

    private void initsession() {
        //年视图展开
        tvMonthDay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!calendarLayout.isExpand()) {
                    calendarView.showYearSelectLayout(mYear);
                    return;
                }
                calendarView.showYearSelectLayout(mYear);
                tvLunar.setVisibility(View.GONE);
                tvYear.setVisibility(View.GONE);
                tvMonthDay.setText(String.valueOf(mYear));
                mYear = calendarView.getCurYear();
            }
        });

        recyclerViewEvent.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

                if (!recyclerView.canScrollVertically(-1)) {
                    if (calendarLayout.isExpand()) {
                        //到顶部才收缩
                        calendarLayout.shrink();
                        ByeBurgerBehavior.from(floatAddPlan).show();
                    }
                    //顶
                } else if (!recyclerView.canScrollVertically(1)) {

                    //底部
                } else if (dy < 0) {
                    //上滑
                    if (!calendarLayout.isExpand()) {
                        calendarLayout.expand();
                        //显示float
                        ByeBurgerBehavior.from(floatAddPlan).hide();
                    }
                } else if (dy > 0) {
                    //下滑

                }

            }
        });
        //添加计划
        floatAddPlan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(WorkPlanEditActivity.class,false);
            }
        });

    }

    private void initrecyclerview() {

        eventListAdpter = new MyEventListAdpter();
        recyclerViewEvent.setAdapter(eventListAdpter);
        recyclerViewEvent.setLayoutManager(new LinearLayoutManager(this));


    }

    /**
     * 该方法为初始化只是排除当前月份是否有日程
     */
    private void initcaleder() {
        List<Calendar> schemes = new ArrayList<>();
        int year = calendarView.getCurYear();
        int month = calendarView.getCurMonth();
        //哪天有事就添加到哪天
        for (Event event : eventLists) {
            if (isCuurentMonth(month, event.getDate())) {
                schemes.add(getSchemeCalendar(year, month, event.getDayofmoth(), 0xFFe69138, "事"));
            }

        }
        calendarView.setSchemeDate(schemes);

    }

    /**
     * 回执更新视图时调用
     */
    private void resmuecaleder() {
        List<Calendar> schemes = new ArrayList<>();
        int year = calendarView.getSelectedCalendar().getYear();
        int month = calendarView.getSelectedCalendar().getMonth();
        //哪天有事就添加到哪天
        for (Event event : eventLists) {
            if (isCuurentMonth(month, event.getDate())) {
                schemes.add(getSchemeCalendar(year, month, event.getDayofmoth(), 0xFFe69138, "事"));
            }

        }
        calendarView.setSchemeDate(schemes);

    }

    /**
     * 只有再正确的月份才显示日程标识
     *
     * @param month
     * @param date
     * @return
     */
    private boolean isCuurentMonth(int month, String date) {

        if (month == getMonthByData(date) && calendarView.getCurYear() == getYearByData(date)) {
            return true;
        } else {
            return false;
        }
    }

    /***
     * 根据stringdate获取时间
     * @param date
     * @return
     */
    private int getMonthByData(String date) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE);
        Date time = null;
        try {
            time = dateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        calendar.setTime(time);
        return calendar.get(java.util.Calendar.MONTH) + 1;
    }

    /***
     * 根据stringdate获取时间
     * @param date
     * @return
     */
    private int getYearByData(String date) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE);
        Date time = null;
        try {
            time = dateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        calendar.setTime(time);
        return calendar.get(java.util.Calendar.YEAR);
    }

    /**
     * 获取日期标记
     *
     * @param year
     * @param month
     * @param day
     * @param color
     * @param text
     * @return
     */
    private Calendar getSchemeCalendar(int year, int month, int day, int color, String text) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        calendar.setScheme(text);
        calendar.addScheme(new Calendar.Scheme());
        calendar.addScheme(0xFF008800, "假");
        calendar.addScheme(0xFF008800, "节");
        return calendar;
    }

    @Override
    protected void initdata() {
        //请求所有的事件
        MyApplication.getClient().findAllPlan(1);
    }

    @Override
    protected void onResume() {
        super.onResume();
        recyclerViewEvent.removeAllViews();
        //请求所有的事件
        resmuecaleder();
        MyApplication.getClient().findAllPlan(1);
    }

    @Override
    protected int setlayout() {
        return R.layout.activity_work_plan_list;
    }

    /**
     * 获取所有的事件
     *
     * @param eva 实体
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getAllEvents(GetAllEvent eva) {
        if (eva.isOk()) {
            EventList eventList = eva.getBean();
            if (eventList.getStatus() != 1) {
                ToastUtils.showToast("获取数据失败");
                return;
            }
            eventLists = eventList.getData();
            initcaleder();
            selectday = calendarView.getSelectedCalendar().getDay();
            //遍历筛选然后加载数据
            eventListAdpter.setEvents(getCuurentEvents());
            eventListAdpter.notifyDataSetChanged();

        }
    }


    @Override
    public void onDateSelected(Calendar calendar, boolean isClick) {
        //选中的日子
        if (isClick) {
            selectday = calendar.getDay();
            recyclerViewEvent.removeAllViews();
            eventListAdpter.setEvents(getCuurentEvents());
            eventListAdpter.notifyDataSetChanged();
        }
        tvLunar.setVisibility(View.VISIBLE);
        tvYear.setVisibility(View.VISIBLE);
        tvMonthDay.setText(calendar.getMonth() + "月" + calendar.getDay() + "日");
        tvYear.setText(String.valueOf(calendar.getYear()));
        tvCurrentDay.setText(String.valueOf(calendar.getDay()));
        tvLunar.setText(calendar.getLunar());
        mYear = calendar.getYear();
        updateDatae();
    }

    /**
     * 更新当前的位置
     */
    private void updateDatae() {
        List<Calendar> schemes = new ArrayList<>();
        int year = calendarView.getCurYear();
        int month = calendarView.getSelectedCalendar().getMonth();
        //哪天有事就添加到哪天
        for (Event event : eventLists) {
            if (isCuurentMonth(month, event.getDate())) {
                schemes.add(getSchemeCalendar(year, month, event.getDayofmoth(), 0xFFe69138, "事"));
            }

        }
        calendarView.setSchemeDate(schemes);
    }

    @Override
    public void onYearChange(int year) {
        //滑动选中的年份
        mYear = year;
        tvMonthDay.setText(String.valueOf(year));
    }

    /**
     * 获取对应天数的事件
     * 1.新镇条件 月份
     *
     * @return
     */
    public List<Event> getCuurentEvents() {
        List<Event> cacheevent = new ArrayList<>();
        int month = calendarView.getSelectedCalendar().getMonth();
        for (Event event : eventLists) {
            if (event.getDayofmoth() == selectday && month == getMonthByData(event.getDate())) {
                cacheevent.add(event);
            }
        }
        return cacheevent;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.list_top_menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId())
        {
            case R.id.action_table:
                //进入即结束
                startActivity(WorkPlanActivity.class,true);
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
